# -*- coding: latin-1 -*-

from Products.CMFCore.utils import getToolByName

from Products.Archetypes.public import listTypes
from Products.Archetypes.Extensions.utils import installTypes, install_subskin
from Products.mxmContacts.config import PROJECTNAME, GLOBALS

from StringIO import StringIO

skin_names = ('mxm_contacts',)

def uninstall(self):
    "Just remove skin names from layers"
    out=StringIO()
    skinsTool = getToolByName(self, 'portal_skins')
    skins = skinsTool.getSkinSelections()
    for skin in skins:
        path = skinsTool.getSkinPath(skin)
        path = [itm.strip() for itm in path.split(',')]
        path = ','.join([n for n in path if not n in skin_names])
        skinsTool.addSkinSelection(skin, path)
    out.write('Uninstalled succesfully\n')
    return out.getvalue()


def install(self):
    out = StringIO()

    installTypes(self, out, listTypes(PROJECTNAME), PROJECTNAME)

    install_subskin(self, out, GLOBALS)
    
    # modify mxmContacts FTI settings
    portal_types = getToolByName(self, 'portal_types')
    for type in listTypes(PROJECTNAME):
        if type["meta_type"] not in "mxmContacts":
            mxm_type = getattr(portal_types, type["meta_type"])
            viewname = "mxmContacts_%s%s" % (type["meta_type"].split("mxmContacts")[1].lower(), "_view")
            mxm_type.default_view = viewname
            mxm_type.immediate_view = viewname
            mxm_type._aliases["(Default)"] = viewname
            mxm_type._aliases["view"] = viewname
            out.write("Modified %s FTI settings" % mxm_type)       
            
    out.write("Successfully installed %s." % PROJECTNAME)
    return out.getvalue()
